<?php
/**
 * Copyright (c) 2003-08  PHPWind.net. All rights reserved.
 * 
 * @filename: install.php
 * @author: Noizy Sky_hold Linzuzhu Fengyu
 * @modify: 2008-5-6
 */
error_reporting(E_ERROR | E_PARSE);
@set_magic_quotes_runtime(0);
function_exists('date_default_timezone_set') && date_default_timezone_set('Etc/GMT+0');

$defined_vars = get_defined_vars();
foreach ($defined_vars as $_key => $_value) {
	if (!in_array($_key,array('GLOBALS','_POST','_GET','_COOKIE','_SERVER'))) {
		${$_key} = '';
		unset(${$_key});
	}
}

define('R_P',getdirname(__FILE__));
define('D_P',R_P);

$_POST = (array)$_POST; $_GET = (array)$_GET;
if (!get_magic_quotes_gpc()) {
	Add_S($_POST);
	Add_S($_GET);
}
foreach ($_POST as $_key => $_value) {
	!preg_match('/^\_/',$_key) && ${$_key} = $_POST[$_key];
}
foreach($_GET as $_key => $_value){
	!preg_match('/^\_/',$_key) && ${$_key} = $_GET[$_key];
}
!$_SERVER['PHP_SELF'] && $_SERVER['PHP_SELF'] = $_SERVER['SCRIPT_NAME'];
$selfrpos = strrpos($_SERVER['PHP_SELF'],'/');
$basename = substr($_SERVER['PHP_SELF'],$selfrpos+1);
$bbsurl = 'http://'.$_SERVER['HTTP_HOST'].substr($_SERVER['PHP_SELF'],0,$selfrpos);
$wind_version = '6.3.2';
$crlf = GetCrlf();

require_once(R_P.'lang/install_lang.php');
$stepmsg = $backmsg = $input = $log = $gojs = $gourl = '';
$systitle = $lang['title_install'];
$syslogo = 'install';
if ($step) {
	$stepmsg = $lang["step_$step"];
	$stepleft = $lang["step_{$step}_left"];
	$stepright = $lang["step_{$step}_right"];
}
ob_start();
require_once(R_P.'lang/header.htm');
$steptitle = $step;
file_exists(D_P.'data/install.lock') && Promptmsg('have_file');
$footer = false;
if (in_array($step,array(4,5,'union','resources','finish'))) {
	include_once(D_P.'data/sql_config.php');
	require_once Pcv(R_P."require/db_$database.php");
	$db = new DB($dbhost,$dbuser,$dbpw,$dbname,$pconnect);
	unset($dbhost,$dbuser,$dbpw,$dbname,$pconnect,$manager,$manager_pwd);
}
$step>0 && $step<5 && @unlink(D_P."data/log$step.txt");

if (!$step) {
	require_once(R_P.'require/posthost.php');
	$footer = true;
	$lang['log_install'] = str_replace('{#basename}',$basename,$lang['log_install']);
//	$lang['log_partner'] = PostHost('http://u.phpwind.com/install/partner.php',"url=$_SERVER[HTTP_HOST]$_SERVER[PHP_SELF]");
	for ($i=1;$i<5;$i++) {
		@unlink(D_P."data/log$i.txt");
	}
} elseif ($step==1) {
	$wind_licence = str_replace(array('  ',"\n"),array('&nbsp; ','<br />'),readover('licence.txt'));
	writeover(D_P.'data/log1.txt',$lang['success_1']);
} elseif ($step==2) {
	$w_check = array(
		'attachment', 'attachment/cn_img', 'attachment/photo', 'attachment/thumb', 'attachment/upload',
		'data', 'data/bbscache', 'data/groupdb', 'data/guestcache', 'data/style', 'data/tmp',
		'htm_data', 'template', 'template/admin', 'template/wind'
	);
	$writelog = $fileexist = $writable = '';
	foreach ($w_check as $filename) {
		/*!file_exists(R_P.$filename) && Promptmsg('error_unfind');
		!N_writable(R_P.$filename) && Promptmsg('error_777');*/
		!file_exists(R_P.$filename) && $fileexist .= ",$filename";
		!N_writable(R_P.$filename) && $writable .= ",$filename";
		$writelog .= str_replace('{#filename}',$filename,$lang['success_2'])."\n";
	}
	if ($fileexist) {
		$filenames = substr($fileexist,1);
		Promptmsg('error_unfinds');
	}
	if ($writable) {
		$filenames = substr($writable,1);
		Promptmsg('error_777s');
	}
	$phplinfo = PHP_VERSION;
	$mysqlichecked = $mysqlchecked = '';
	if ($phplinfo>='5.1.0') {
		$mysqlichecked = 'CHECKED';
	} else {
		$mysqlchecked = 'CHECKED';
	}
	writeover(D_P.'data/log2.txt',trim($writelog,"\n"));
} elseif ($step==3) {
	!$manager_email && Promptmsg('error_nothing');
	$mysqlimsg = '';
	$input = "<input type=\"hidden\" name=\"manager_email\" value=\"$manager_email\">";
	if (!file_exists(D_P.'data/sql_config.php') || $_POST['from']!='prompt') {
		if (!N_writable(D_P.'data/sql_config.php')) {
			$filename = 'data/sql_config.php';
			Promptmsg('error_777');
		}
		if (!$dbhost || !$dbuser || !$dbname || !$PW || !$manager || !$manager_pwd) {
			Promptmsg('error_nothing');
		}
		if ($manager_pwd!==$manager_ckpwd) {
			Promptmsg('error_ckpwd');
		}
		$manager_pwd = md5($manager_pwd);
		$charset = str_replace('-','',$lang['db_charset']);
		require R_P.'require/db_mysql.php';
		$db = new DB($dbhost,$dbuser,$dbpw,'',$pconnect);
		$mysqlinfo = mysql_get_server_info($db->sql);
		if ($database=='mysqli') {
			if ($mysqlinfo<'4.1.3') {
				$database = 'mysql'; $mysqlimsg = $lang['error_mysqli'];
			} else {
				ob_end_clean();
				if (Pwloaddl('mysqli')===false) {
					$database = 'mysql'; $mysqlimsg = $lang['error_mysqli'];
				}
				ob_start();
				require(R_P.'lang/header.htm');
				$steptitle = $step;
			}
		}
		
		$manager = array($manager); $manager_pwd = array($manager_pwd);
		$newconfig = array(
			'dbhost' => $dbhost,
			'dbuser' => $dbuser,
			'dbpw' => $dbpw,
			'dbname' => $dbname,
			'database' => $database,
			'PW' => $PW,
			'pconnect' => 0,
			'charset' => $charset,
			'manager' => $manager,
			'manager_pwd' => $manager_pwd,
			'db_hostweb' => 1,
			'attach_url' => array()
		);
		require_once(R_P.'require/updateset.php');
		write_config($newconfig); unset($newconfig);
		
		if ($mysqlinfo>'4.1') {
			mysql_query("CREATE DATABASE IF NOT EXISTS `$dbname` DEFAULT CHARACTER SET $charset");
		} else {
			mysql_query("CREATE DATABASE IF NOT EXISTS `$dbname`");
		}
		if (mysql_errno()) {
			Promptmsg('error_nodatabase');
		} elseif ($query = mysql_query("SELECT COUNT(*) FROM `$dbname`.{$PW}members")) {
			Promptmsg('have_install',3);
		}
		mysql_select_db($dbname);
	} else {
		include D_P.'data/sql_config.php';
		require Pcv(R_P."require/db_$database.php");
		$db = new DB($dbhost,$dbuser,$dbpw,$dbname,$pconnect);
	}
	$timestamp = time();
	$t		 = getdate($timestamp+8*3600);
	$tdtime  = (floor($timestamp/3600)-$t['hours'])*3600;
	$lang['db_bbsurl'] = $bbsurl;
	$lang['db_manager'] = $manager[0];
	$content = str_replace(array("\r","\n\n",";\n"),array('',"\n",";<wind>\n"),trim(readover(R_P.'lang/install_wind.sql')," \n"));
	$content = preg_replace("/{#(.+?)}/eis",'$lang[\\1]',$content).'<wind>';
	$content = explode("\n",$content);
	$writearray = array($lang['success_3']);
	@set_time_limit(200);
	$writearray = SQLCreate($content);
	$db->update("INSERT INTO pw_members (username,password,email,publicmail,groupid,memberid,regdate,receivemail) VALUES ('$manager[0]','$manager_pwd[0]','$manager_email','1','3','8','$timestamp','1')");
	$uid = $db->insert_id();
	$db->update("INSERT INTO pw_memberdata (uid,lastvisit,thisvisit) VALUES ('$uid','$timestamp','$timestamp')");
	$db->update("INSERT INTO pw_bbsinfo (id,newmember,totalmember,tdtcontrol) VALUES ('1','$manager[0]','1','$tdtime')");
	$db->update("INSERT INTO pw_administrators(uid,username,groupid,groups) VALUES('$uid','$manager[0]','3','')");
	writeover(D_P.'data/log3.txt',implode("\n",$writearray)."\n$lang[success_3_2]");
} elseif ($step==4) {
	$sqlcache = readover(D_P.'data/install_sys.sql');
	$sqlcache && SQLUpdate($sqlcache,$step);
	$forum_pa = array('1'=>Char_cv(trim($_POST['forums1']),1),'2'=>Char_cv(trim($_POST['forums2']),1),'3'=>Char_cv(trim($_POST['forums3']),1),'4'=>Char_cv(trim($_POST['forums4']),1));
	!$forum_pa[1] && Promptmsg('error_forums1');
	!$forum_pa[2] && Promptmsg('error_forums2');
	if (!$forum_pa[3]) {
		$forum_pa[4] && Promptmsg('error_forums3');
		unset($forum_pa[3]);
	}
	if (!$forum_pa[4]) {
		$forum_pa[3] && Promptmsg('error_forums4');
		unset($forum_pa[4]);
	}
	$writelog = '';
	$forum_sql = array();
	foreach ($forum_pa as $fid => $value) {
		if ($value) {
			if (in_array($fid,array(1,3))) {
				$fup = 0; $childid = 1; $type = 'category'; $f_type = $allowvisit = '';
			} else {
				$childid = 0; $f_type = $type = 'forum';
				$fup = $fid-1;
				$allowvisit = '';
			}
			$writelog .= str_replace('{#value}',$value,$lang['success_4'])."\n";
			$forum_sql[$fid] = "('$fid','$fup','$childid','$type','$value','3','$allowvisit','$f_type','0','1')";
		}
	}
	if (!empty($forum_sql)) {
		$db->update('REPLACE INTO pw_forums(fid,fup,childid,type,name,allowtype,allowvisit,f_type,cms,ifhide) VALUES '.implode(',',$forum_sql));
		$db->update("REPLACE INTO pw_forumdata(fid) VALUES ('".implode("'),('",array_keys($forum_sql))."')");
	}
	$uninstalldb = (array)HackList();
	writeover(D_P.'data/log4.txt',$writelog.$lang['success_4_2']);
} elseif ($step==5) {
	$syscachefile = D_P.'data/install_sys.sql';
	$sqlcache = readover($syscachefile);
	$createcache = '';
	$writearray = $db_hackdb = array();
	if (is_array($hackdb)) {
		$uninstalldb = (array)HackList();
		foreach ($hackdb as $value) {
			if ($uninstalldb[$value][0]) {
				$db_hackdb[$value] = $uninstalldb[$value];
				$createcache .= trim(readover(R_P."hack/$value/sql.txt")," \n")."\n";
			}
		}
		if ($createcache) {
			$createcache = explode("\n",str_replace(array("\r","\n\n",";\n"),array('',"\n",";<wind>\n"),$createcache.'<wind>'));
			if ($createcache) {
				$writearray = SQLCreate($createcache,1);
				$hacksqlcache = readover(D_P.'data/install_hack.sql');
				if ($hacksqlcache) {
					$sqlcache .= $hacksqlcache;
					writeover($syscachefile);
					@unlink(D_P.'data/install_hack.sql');
				}
				$db_hackdb = addslashes(serialize($db_hackdb));
			}
		}
		$db->update("REPLACE INTO pw_config(db_name,db_value) VALUES ('db_hackdb','$db_hackdb')");
		$writearray[] = $lang['success_5'];
	}
	$sqlcache && SQLUpdate($sqlcache,$step);
	$writeinto = str_pad('<?die;?>',96)."\n";
	writeover(D_P.'data/bbscache/online.php',$writeinto);
	writeover(D_P.'data/bbscache/guest.php',$writeinto);
	writeover(D_P.'data/bbscache/olcache.php',"<?php\r\n\$userinbbs=1;\r\n\$guestinbbs=0;\r\n?>");
	$writearray = implode('<wind>',$writearray);
	for ($i=1;$i<5;$i++) {
		$log .= readover(D_P."data/log$i.txt")."\n";
	}
	$log = str_replace("\n",'<wind>',$log).$lang['success_5_2'];
} elseif ($step=='union') {
	$sqlcache = readover(D_P.'data/install_sys.sql');
	$sqlcache && SQLUpdate($sqlcache,6);
	$steptitle = '!';
	$db_hash = '';
	mt_srand((double)microtime()*1000000);
	$rand = '0123%^&*45ICV%^&*B6789qazw~!@#$sxedcrikolpQWER%^&*TYUNM';
	$randlen = strlen($rand);
	for ($i=0;$i<10;$i++) {
		$db_hash .= $rand[mt_rand(0,$randlen)];
	}
	$db->update("REPLACE INTO pw_config(db_name,db_value) VALUES ('db_hash','$db_hash')");
	$db->update("REPLACE INTO pw_config(db_name,db_value) VALUES ('db_windmagic','$db_windmagic')");
	$db->update("REPLACE INTO pw_styles SET sid='1',name='wind',stylepath='wind',tplpath='wind',yeyestyle='1',bgcolor='#fff',linkcolor='#2B76B0',tablecolor='#76BAC2',tdcolor='#D5E5E8',tablewidth='98%',mtablewidth='98%',headcolor='#CEECF0',headborder='#AED6DB',headfontone='#005368',headfonttwo='#5495A0',cbgcolor='#F7F7F7',cbgborder='#daddbf',cbgfont='#AFCE50',forumcolorone='#ffffff',forumcolortwo='#F4FBFF'");
} elseif ($step=='resources') {
	$sqlcache = readover(D_P.'data/install_sys.sql');
	$sqlcache && SQLUpdate($sqlcache,7);
	$steptitle = '!';
	mt_srand((double)microtime()*1000000);
	$db_siteid      = generatestr(16);
	$db_siteownerid = generatestr(18);
	$db_sitehash = '10'.SitStrCode(md5($db_siteid.$db_siteownerid),md5($db_siteownerid.$db_siteid));
	$banners = (int)$banners; $atcbottoms = (int)$atcbottoms; $footers = (int)$footers;
	if ($banners || $atcbottoms || $footers) {
	//	echo "<img src=\"http://init.phpwind.com/init_agent.php?sitehash=$db_sitehash&v=$wind_version&c=$ceversion&referer=$_SERVER[HTTP_HOST]&banner=$banners&atcbottom=$atcbottoms&footer=$footers\" width=\"0\" height=\"0\">";
	}
	$db->update("REPLACE INTO pw_config(db_name,db_value) VALUES ('db_siteid','$db_siteid')");
	$db->update("REPLACE INTO pw_config(db_name,db_value) VALUES ('db_siteownerid','$db_siteownerid')");
	$db->update("REPLACE INTO pw_config(db_name,db_value) VALUES ('db_sitehash','$db_sitehash')");
	$stepright = $lang['success'];
} elseif ($step=='finish') {
	$timestamp = time();
	$sqlcache = readover(D_P.'data/install_sys.sql');
	$sqlcache && SQLUpdate($sqlcache,$step);
	$steptitle = '!';
	if (!is_writeable($basename)) {
		$lang['success_install'] .= "<br /><small><font color=\"red\">$lang[error_delinstall]</font></small>";
	}
	$lang['success_install'] = preg_replace("/{#(.+?)}/eis",'$\\1',$lang['success_install']);
	require(R_P.'lang/install.htm');
	require_once(R_P.'admin/cache.php');
	if ($writemsg) {
		require_once(R_P.'require/msg.php');
		writenewmsg(array($manager,'0',$lang['log_unionmsgt'],$timestamp,$lang['log_unionmsgc'],'N'),1);
	}
	updatecache();
	updatemedal_list(); updatecache_cnc();
	writeover(D_P.'data/install.lock','LOCKED');
	for ($i=1;$i<5;$i++) {
		@unlink(D_P."data/log$i.txt");
	}
	@unlink(D_P.'data/install_sys.sql');
	@unlink($basename);
	footer();
}
require(R_P.'lang/install.htm');footer();
########################## FUNCTION ##########################
function updatecache_cnc(){
	global $db;
	$cnclassdb = array();
	$query = $db->query('SELECT cid,cname,cnsum FROM pw_cnclass ORDER BY cid');
	while ($rt = $db->fetch_array($query)) {
		$cnclassdb[$rt['cid']] = array('cname' => $rt['cname'],'cnsum' => $rt['cnsum']);
	}
	writeover(D_P."data/bbscache/cn_class.php","<?php\r\n\$cnclassdb=".pw_var_export($cnclassdb).";\r\n?>");
}
function pw_var_export($input,$t = null) {
	$output = '';
	if (is_array($input)) {
		$output .= "array(\r\n";
		foreach ($input as $key => $value) {
			$output .= $t."\t".pw_var_export($key,$t."\t").' => '.pw_var_export($value,$t."\t");
			$output .= ",\r\n";
		}
		$output .= $t.')';
	} elseif (is_string($input)) {
		$output .= "'".str_replace(array("\\","'"),array("\\\\","\'"),$input)."'";
	} elseif (is_int($input) || is_double($input)) {
		$output .= "'".(string)$input."'";
	} elseif (is_bool($input)) {
		$output .= $input ? 'true' : 'false';
	} else {
		$output .= 'NULL';
	}
	return $output;
}
function substrs($content,$length,$add='Y'){
	if ($length && strlen($content)>$length) {
		global $db_charset;
		if ($db_charset!='utf-8') {
			$retstr = '';
			for ($i=0;$i<$length-2;$i++) {
				$retstr .= ord($content[$i]) > 127 ? $content[$i].$content[++$i] : $content[$i];
			}
			return $retstr.($add=='Y' ? ' ..' : '');
		}
		return utf8_trim(substr($content,0,$length)).($add=='Y' ? ' ..' : '');
	}
	return $content;
}
function utf8_trim($str) {
	$hex = '';
	$len = strlen($str)-1;
	for ($i=$len;$i>=0;$i-=1) {
		$ch = ord($str[$i]);
		$hex .= " $ch";
		if (($ch & 128)==0 || ($ch & 192)==192) {
			return substr($str,0,$i);
		}
	}
	return $str.$hex;
}
function PwStrtoTime($time){
	global $db_timedf;
	return function_exists('date_default_timezone_set') ? strtotime($time) - $db_timedf*3600 : strtotime($time);
}
function GetLang($lang,$EXT="php"){
	global $tplpath;
	if (file_exists(R_P."template/$tplpath/lang_$lang.$EXT")) {
		return R_P."template/$tplpath/lang_$lang.$EXT";
	} elseif (file_exists(R_P."template/wind/lang_$lang.$EXT")) {
		return R_P."template/wind/lang_$lang.$EXT";
	} else {
		exit("Can not find lang_$lang.$EXT file");
	}
}
function adminmsg(){}
function Showmsg(){}
function Char_cv($msg,$unhtml=null){
	$msg = str_replace(array("\t","\r","\n",'  '),array('','','','&nbsp; '),$msg);
	empty($unhtml) && $msg = str_replace(array('<','>'),array('&lt;','&gt;'),$msg);
	return $msg;
}
function HackList(){
	$hackdb = array();
	if ($fp = opendir(R_P.'hack')) {
		$infodb = array();
		while (($hackdir = readdir($fp))) {
			if (strpos($hackdir,'.')===false) {
				$hackopen = 0;
				$hackname = $hackdir;
				$filedata = readover(R_P."hack/$hackdir/info.xml");
				if (preg_match('/\<hackname\>(.+?)\<\/hackname\>\s+\<ifopen\>(.+?)\<\/ifopen\>/is',$filedata,$infodb)) {
					$infodb[1] && $hackname = Char_cv(str_replace(array("\n"),'',$infodb[1]));
					$hackopen = (int)$infodb[2];
				}
				$hackdb[$hackdir] = array($hackname,$hackdir,$hackopen);
			}
		}
		closedir($fp);
	}
	return $hackdb;
}
function SitStrCode($string,$key,$action='ENCODE'){
	$string	= $action == 'ENCODE' ? $string : base64_decode($string);
	$len	= strlen($key);
	$code	= '';
	for($i=0; $i<strlen($string); $i++){
		$k		= $i % $len;
		$code  .= $string[$i] ^ $key[$k];
	}
	$code = $action == 'DECODE' ? $code : str_replace('=','',base64_encode($code));
	return $code;
}
function generatestr($len) {
	mt_srand((double)microtime() * 1000000);
    $keychars = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWYXZ";
	$maxlen = strlen($keychars)-1;
	$str = '';
	for ($i=0;$i<$len;$i++){
		$str .= $keychars[mt_rand(0,$maxlen)];
	}
	return substr(md5($str.time().$_SERVER['HTTP_USER_AGENT'].$GLOBALS['db_hash']),0,$len);
}
function SQLUpdate($sqlcache,$step) {
	global $db;
	$sqlarray = explode(';<wind>',$sqlcache);
	$count = count($sqlarray);
	if ($count>0) {
		if ($count>50 && (int)$step>0) {
			$cutnum = ceil($count/$step)*($step-1);
			$cutnum<50 && $cutnum=0;
		} else {
			$cutnum = 0;
		}
		$num = 0; $cutcache = '';
		foreach ($sqlarray as $value) {
			if ($value) {
				$lowquery = strtolower(substr($value,0,5));
				if (in_array($lowquery,array('alter','inser','repla'))) {
					if ($cutnum) {
						$num++;
						if ($num>$cutnum) break;
					}
					$cutcache .= "$value;<wind>";
					$db->query($value);
				}
			}
		}
		if ($cutcache) {
			$writedata = str_replace($cutcache,'',$sqlcache);
			writeover(D_P.'data/install_sys.sql',$writedata);
		}
	} else {
		return false;
	}
	return true;
}
function SQLCreate($sqlarray,$hack = null) {
	global $db,$charset,$writearray,$lang;
	$query = $updatesql = '';
	$cachename = empty($hack) ? 'sys' : 'hack';
	foreach ($sqlarray as $value) {
		$value = trim($value," \t");
		if ($value && $value[0]!='#') {
			$query .= $value;
			if (substr($value,-7)==';<wind>') {
				$lowquery = strtolower(substr($query,0,5));
				$checkdrop = CheckDrop($value);
				if (in_array($lowquery,array('drop ','creat'))) {
					if ($cachename=='sys' || $checkdrop) {
						if ($lowquery=='creat') {
							$tablename = trim(substr($query,0,strpos($query,'(')));
							$tablename = substr($tablename,strrpos($tablename,' ')+1);
							$writearray[] = str_replace('{#tablename}',$tablename,$lang['success_3_1']);
							$search = trim(substr(strrchr($value,')'),1));
							$tabtype = substr(strchr($search,'='),1);
							$tabtype = substr($tabtype,0,strpos($tabtype,strpos($tabtype,' ') ? ' ' : ';'));
							if ($db->server_info() >= '4.1') {
								$replace = "ENGINE=$tabtype".($charset ? " DEFAULT CHARSET=$charset" : '').';';
							} else {
								$replace = "TYPE=$tabtype;";
							}
							$query = str_replace(array($search,'<wind>'),array($replace,''),$query);
						} else {
							$query = str_replace('<wind>','',$query);
						}
						$db->query($query);
					}
				} elseif ((in_array($lowquery,array('inser','repla')) && ($cachename=='sys' || $checkdrop)) || ($lowquery=='alter' && $cachename!='sys' && $checkdrop && strpos(strtolower($query),'drop')===false)) {
					$lowquery=='inser' && $query = 'REPLACE '.substr($query,6);
					$updatesql .= $query;
				}
				$query = '';
			}
		}
	}
	$updatesql && writeover(D_P."data/install_$cachename.sql",$updatesql);
	return $writearray;
}
function readover($filename,$method='rb'){
	strpos($filename,'..')!==false && exit('Forbidden');
	$filedata = '';
	if ($handle = @fopen($filename,$method)) {
		flock($handle,LOCK_SH);
		$filedata = @fread($handle,filesize($filename));
		fclose($handle);
	}
	return $filedata;
}
function writeover($filename,$data,$method="rb+",$iflock=1,$check=1,$chmod=1){
	$check && strpos($filename,'..')!==false && exit('Forbidden');
	touch($filename);
	$handle=@fopen($filename,$method);
	if($iflock){
		flock($handle,LOCK_EX);
	}
	fwrite($handle,$data);
	if($method=="rb+") ftruncate($handle,strlen($data));
	fclose($handle);
	$chmod && @chmod($filename,0777);
}
function Add_S(&$array){
	if (is_array($array)) {
		foreach ($array as $key => $value) {
			if (!is_array($value)) {
				$array[$key] = addslashes($value);
			} else {
				Add_S($array[$key]);
			}
		}
	}
}
function Promptmsg($msg,$tostep=null){
	@extract($GLOBALS, EXTR_SKIP);
	require(R_P.'lang/install_lang.php');
	$lang[$msg] && $msg = $lang[$msg];
	$msg = preg_replace("/{#(.+?)}/eis",'$\\1',$msg);
	$url = $backurl = 'javascript:history.go(-1);';
	$backmsg = !empty($tostep) ? $stepleft : '';
	if (!$backmsg) {
		$lang['last'] = $lang['back'];
		@unlink("log$step.txt");
	} else {
		$url = "document.getElementById('install').submit();";
	}
	require(R_P.'lang/promptmsg.htm');
	footer();
}
function footer(){
	global $footer;
	require_once(R_P.'lang/footer.htm');
	$output = trim(str_replace(array('<!--<!---->','<!---->',"\r",substr(R_P,0,-1)),'',ob_get_contents()),"\n");
	ob_end_clean();
	ob_start();
	echo $output;unset($output);exit;
}
function Pcv($filename,$ifcheck=1){
	$tmpname = strtolower($filename);
	if (strpos($tmpname,'http://')!==false || ($ifcheck && strpos($tmpname,'..')!==false)) {
		exit('Forbidden');
	}
	return $filename;
}
function CheckDrop($query){
	global $db;
	require_once(R_P.'admin/table.php');
	list($pwdb) = N_getTabledb();
	$next = true;
	foreach ($pwdb as $value) {
		if (strpos(strtolower($query),strtolower($value))!==false) {
			$next = false;
			break;
		}
	}
	return $next;
}
function getdirname($path=null){
	if (!empty($path)) {
		if (strpos($path,'\\')!==false) {
			return substr($path,0,strrpos($path,'\\')).'/';
		} elseif (strpos($path,'/')!==false) {
			return substr($path,0,strrpos($path,'/')).'/';
		}
	}
	return './';
}
function GetCrlf(){
	return GetPlatform()=='win' ? "\r\n" : "\n";
}
function GetPlatform(){
	if (strpos($_SERVER['HTTP_USER_AGENT'],'Win')!==false) {
		return 'win';
	} elseif (strpos($_SERVER['HTTP_USER_AGENT'],'Mac')!==false) {
		return 'mac';
	} elseif (strpos($_SERVER['HTTP_USER_AGENT'],'Linux')!==false) {
		return 'linux';
	} elseif (strpos($_SERVER['HTTP_USER_AGENT'],'Unix')!==false) {
		return 'unix';
	} elseif (strpos($_SERVER['HTTP_USER_AGENT'],'OS/2')!==false) {
		return 'os2';
	} else {
		return '';
	}
}
function UserAgentMsg(){
	//Copyright (c) 2003-08 PHPWind
	//return Browser Agent and Version
	if (preg_match('/Opera(\/| )([0-9]\.[0-9]{1,2})/',$_SERVER['HTTP_USER_AGENT'],$ver)) {
		return array('opera',$ver[2]);
	} elseif (preg_match('/MSIE ([0-9]\.[0-9]{1,2})/',$_SERVER['HTTP_USER_AGENT'],$ver)) {
		return array('ie',$ver[1]);
	} elseif (preg_match('/OmniWeb\/([0-9]\.[0-9]{1,2})/',$_SERVER['HTTP_USER_AGENT'],$ver)) {
		return array('omniweb',$ver[1]);
	} elseif (preg_match('/(Konqueror\/)(.*)(;)/',$_SERVER['HTTP_USER_AGENT'],$ver)) {
		return array('konqueror',$ver[2]);
	} elseif (preg_match('/Mozilla\/([0-9]\.[0-9]{1,2})/',$_SERVER['HTTP_USER_AGENT'],$ver1)) {
		if (preg_match('/Safari\/([0-9]*)/',$_SERVER['HTTP_USER_AGENT'],$ver2)) {
			return array('safari',"$ver1[1].$ver2[1]");
		}
		return array('mozilla',$ver1[1]);
	} else {
		return array();
	}
}
function N_writable($pathfile) {
	//Copyright (c) 2003-08 PHPWind
	//fix windows acls bug
	$unlink = false;
	substr($pathfile,-1)=='/' && $pathfile = substr($pathfile,0,-1);
	if (is_dir($pathfile)) {
		$unlink = true;
		mt_srand((double)microtime()*1000000);
		$pathfile = "$pathfile/pw_".uniqid(mt_rand()).'.tmp';
	}
	$fp = @fopen($pathfile,'ab');
	if ($fp===false) return false;
	fclose($fp);
	if ($unlink) @unlink($pathfile);
	return true;
}
function Pwloaddl($mod,$ckfunc='mysqli_get_client_info'){//20080714
	return extension_loaded($mod) && $ckfunc && function_exists($ckfunc) ? true : false;
}
?>